<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>舵机控制系统</title>
    <style>
        :root {
            --primary-color: #2196F3;
            --hover-color: #1976D2;
            --background: #f5f5f5;
        }

        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: var(--background);
        }

        .container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .panel {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .servo-item, .action-item {
            padding: 15px;
            margin: 10px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        button {
            background: var(--primary-color);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
        }

        button:hover {
            background: var(--hover-color);
        }

        input[type="number"] {
            width: 80px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .file-ops {
            margin-bottom: 20px;
        }

        #jsonFile {
            display: none;
        }

        .status-message {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            display: none;
        }

        .success {
            background: #dff0d8;
            color: #3c763d;
        }

        .error {
            background: #f2dede;
            color: #a94442;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 舵机控制面板 -->
        <div class="panel">
            <h2>舵机控制</h2>
            <div class="file-ops">
                <button onclick="executeAllActions()">执行全部动作</button>
            </div>
            <div id="servoList"></div>
        </div>

        <!-- 文件上传面板 -->
        <div class="panel">
            <h2>文件上传</h2>
            <div class="file-ops">
                <form id="uploadForm" enctype="multipart/form-data">
                    <input type="file" name="file" id="fileInput">
                    <button type="button" onclick="uploadFile()">上传文件</button>
                    <button type="button" onclick="uploadjson()">上传并挂载json文件</button>
                </form>
            </div>
            <div class="file-list">
                <h3>可用动作文件:</h3>
                <div id="fileList"></div>
            </div>
        </div>
    </div>

    <div id="statusMessage" class="status-message"></div>

    <script>
        // 执行全部动作
        async function executeAllActions() {
            try {
                const response = await fetch('/execute_all_actions');
                showMessage(response.statusText);
            } catch (error) {
                showMessage(`执行失败: ${error.statusText}`, true);
            }
        }

        // 上传文件
        function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                showMessage('请选择一个文件', true);
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            fetch('/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                showMessage(result);
            })
            .catch(error => {
                showMessage(`上传失败: ${error.message}`, true);
            });
        }
        // 上传执行文件
        function uploadjson() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                showMessage('请选择一个文件', true);
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            fetch('/upload_json', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                showMessage(result);
            })
            .catch(error => {
                showMessage(`上传失败: ${error.message}`, true);
            });
        }

        // 显示消息
        function showMessage(message, isError = false) {
            const statusMessage = document.getElementById('statusMessage');
            statusMessage.textContent = message;
            if (isError) {
                statusMessage.classList.add('error');
                statusMessage.classList.remove('success');
            } else {
                statusMessage.classList.add('success');
                statusMessage.classList.remove('error');
            }
            statusMessage.style.display = 'block';
        }

    // 初始化时加载文件列表
        document.addEventListener('DOMContentLoaded', loadFileList);

        // 加载文件列表
        async function loadFileList() {
            try {
                const response = await fetch('/get_all_json');
                const files = await response.json();
                renderFileList(files.filter(f => f.endsWith('.json')));
            } catch (error) {
                showMessage(`加载文件列表失败: ${error}`, true);
            }
        }

        // 渲染文件列表
        function renderFileList(files) {
            const container = document.getElementById('fileList');
            container.innerHTML = files.map(file => `
                <div class="file-item">
                    <span>${file}</span>
                    <div class="file-actions">
                        <span class="json-badge">JSON</span>
                        <button onclick="executeFile('${file}')">执行</button>
                        <button onclick="deleteFile('${file}')">删除</button>
                    </div>
                </div>
            `).join('');
        }

        // 执行指定文件
        async function executeFile(filename) {
            try {
                const response = await fetch(`/load_and_run_actions/${filename}`);
                if (!response.ok) throw new Error(response.statusText);
                showMessage(`${filename} 执行成功`);
            } catch (error) {
                showMessage(`${filename} 执行失败: ${error}`, true);
            }
        }

        // 更新上传函数
        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file || !file.name.endsWith('.json')) {
                showMessage('请选择JSON文件', true);
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await fetch('/upload_json', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) throw new Error(response.statusText);
                showMessage(`${file.name} 上传成功`);
                loadFileList(); // 刷新列表
            } catch (error) {
                showMessage(`上传失败: ${error}`, true);
            }
        }

        // 删除文件（前端）
        async function deleteFile(filename) {
            if (!confirm(`确定要删除 ${filename} 吗？`)) return;

            try {
                const safeFilename = encodeURIComponent(filename);
                const response = await fetch(`/remove_action/${safeFilename}`, {
                    method: 'GET'
                });

                if (!response.ok) {
                    throw new Error(response.status === 400 ? '文件删除失败' : '服务器错误');
                }

                showMessage(`${filename} 已删除`);
                loadFileList(); // 刷新文件列表
            } catch (error) {
                showMessage(`删除失败: ${error.message}`, true);
            }
        }

    </script>
</body>
</html>
